from django.contrib.auth import logout
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.models import User
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.template.context import RequestContext
from portal.forms import RegistrationForms

@login_required  #Beautiful annotation
def portal_main_page(request):
    """
    If users are authenticated, direct them to the main page. Otherwise, take
    them to the login page.
    """
    return render_to_response('portal/index.html',context_instance=RequestContext(request))


def main_page(request):
    return HttpResponseRedirect('/portal')

def logout_page(request):
    """
    Log users out and re-direct them to the main page.
    """
    logout(request)
    return HttpResponseRedirect('/')

def login_page(request):
    form = AuthenticationForm(request)
    form.fields['username'].widget.attrs['class'] = "custom_css"
    form.fields['password'].widget.attrs['style'] = "background:red"
    return render_to_response("login.html", {'form':form},
        context_instance=RequestContext(request))

def register_page(request):
    if request.method == 'POST':
        form = RegistrationForms(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password1'],
                email=form.cleaned_data['email']
            )
            return HttpResponseRedirect('/register/success/')
    else:
        form = RegistrationForms()
    variables = RequestContext(request, {'form': form} )
    return render_to_response('registration/register.html',variables)